import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:fl_chart/fl_chart.dart';
import '../providers/mood_provider.dart';
import '../models/mood_record.dart';
import '../models/mood_type.dart';
import '../widgets/custom_app_bar.dart';
import '../constants/app_theme.dart';
import '../constants/app_strings.dart';
import 'dart:math' as math;

/// 趋势分析页面
class AnalyticsScreen extends StatefulWidget {
  const AnalyticsScreen({super.key});

  @override
  State<AnalyticsScreen> createState() => _AnalyticsScreenState();
}

class _AnalyticsScreenState extends State<AnalyticsScreen>
    with TickerProviderStateMixin {
  late TabController _tabController;
  
  /// 时间范围选项
  TimeRange _selectedTimeRange = TimeRange.week;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: AppStrings.get('analytics_title'),
        actions: [
          PopupMenuButton<TimeRange>(
            icon: const Icon(Icons.date_range),
            onSelected: (range) {
              setState(() {
                _selectedTimeRange = range;
              });
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: TimeRange.week,
                child: Text('最近一周'),
              ),
              const PopupMenuItem(
                value: TimeRange.month,
                child: Text('最近一月'),
              ),
              const PopupMenuItem(
                value: TimeRange.quarter,
                child: Text('最近三月'),
              ),
              const PopupMenuItem(
                value: TimeRange.year,
                child: Text('最近一年'),
              ),
            ],
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(
              icon: Icon(Icons.trending_up),
              text: '趋势',
            ),
            Tab(
              icon: Icon(Icons.pie_chart),
              text: '分布',
            ),
            Tab(
              icon: Icon(Icons.insights),
              text: '洞察',
            ),
          ],
        ),
      ),
      body: Consumer<MoodProvider>(
        builder: (context, moodProvider, child) {
          final records = _getFilteredRecords(moodProvider.allRecords);
          
          if (records.isEmpty) {
            return _buildEmptyState();
          }
          
          return TabBarView(
            controller: _tabController,
            children: [
              _buildTrendView(records),
              _buildDistributionView(records),
              _buildInsightsView(records),
            ],
          );
        },
      ),
    );
  }

  /// 获取筛选后的记录
  List<MoodRecord> _getFilteredRecords(List<MoodRecord> records) {
    final now = DateTime.now();
    DateTime startDate;
    
    switch (_selectedTimeRange) {
      case TimeRange.week:
        startDate = now.subtract(const Duration(days: 7));
        break;
      case TimeRange.month:
        startDate = now.subtract(const Duration(days: 30));
        break;
      case TimeRange.quarter:
        startDate = now.subtract(const Duration(days: 90));
        break;
      case TimeRange.year:
        startDate = now.subtract(const Duration(days: 365));
        break;
    }
    
    return records.where((record) {
      return record.createdAt.isAfter(startDate);
    }).toList();
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.analytics_outlined,
            size: 80,
            color: AppTheme.textSecondaryColor,
          ),
          const SizedBox(height: 16),
          Text(
            '暂无数据',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: AppTheme.textSecondaryColor,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '开始记录你的情绪，\n查看个性化的分析报告',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: AppTheme.textSecondaryColor,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建趋势视图
  Widget _buildTrendView(List<MoodRecord> records) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionTitle('情绪趋势'),
          const SizedBox(height: 16),
          _buildMoodTrendChart(records),
          const SizedBox(height: 24),
          _buildSectionTitle('强度变化'),
          const SizedBox(height: 16),
          _buildIntensityTrendChart(records),
          const SizedBox(height: 24),
          _buildSectionTitle('记录频率'),
          const SizedBox(height: 16),
          _buildFrequencyChart(records),
        ],
      ),
    );
  }

  /// 构建分布视图
  Widget _buildDistributionView(List<MoodRecord> records) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionTitle('情绪分布'),
          const SizedBox(height: 16),
          _buildMoodDistributionChart(records),
          const SizedBox(height: 24),
          _buildSectionTitle('强度分布'),
          const SizedBox(height: 16),
          _buildIntensityDistributionChart(records),
          const SizedBox(height: 24),
          _buildSectionTitle('时间分布'),
          const SizedBox(height: 16),
          _buildTimeDistributionChart(records),
        ],
      ),
    );
  }

  /// 构建洞察视图
  Widget _buildInsightsView(List<MoodRecord> records) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionTitle('数据概览'),
          const SizedBox(height: 16),
          _buildStatisticsCards(records),
          const SizedBox(height: 24),
          _buildSectionTitle('情绪模式'),
          const SizedBox(height: 16),
          _buildPatternAnalysis(records),
          const SizedBox(height: 24),
          _buildSectionTitle('标签词云'),
          const SizedBox(height: 16),
          _buildTagCloud(records),
        ],
      ),
    );
  }

  /// 构建章节标题
  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: TextStyle(
        fontSize: 18,
        fontWeight: FontWeight.bold,
        color: AppTheme.textPrimaryColor,
      ),
    );
  }

  /// 构建情绪趋势图表
  Widget _buildMoodTrendChart(List<MoodRecord> records) {
    final chartData = _prepareMoodTrendData(records);
    
    return Container(
      height: 300,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: LineChart(
        LineChartData(
          gridData: FlGridData(
            show: true,
            drawVerticalLine: false,
            horizontalInterval: 1,
            getDrawingHorizontalLine: (value) {
              return FlLine(
                color: AppTheme.dividerColor,
                strokeWidth: 1,
              );
            },
          ),
          titlesData: FlTitlesData(
            show: true,
            rightTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            topTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            bottomTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 30,
                interval: 1,
                getTitlesWidget: (value, meta) {
                  if (value.toInt() < chartData.length) {
                    return Text(
                      chartData[value.toInt()].label,
                      style: TextStyle(
                        color: AppTheme.textSecondaryColor,
                        fontSize: 12,
                      ),
                    );
                  }
                  return const Text('');
                },
              ),
            ),
            leftTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                interval: 2,
                reservedSize: 40,
                getTitlesWidget: (value, meta) {
                  return Text(
                    value.toInt().toString(),
                    style: TextStyle(
                      color: AppTheme.textSecondaryColor,
                      fontSize: 12,
                    ),
                  );
                },
              ),
            ),
          ),
          borderData: FlBorderData(
            show: true,
            border: Border.all(
              color: AppTheme.dividerColor,
              width: 1,
            ),
          ),
          minX: 0,
          maxX: (chartData.length - 1).toDouble(),
          minY: 0,
          maxY: 10,
          lineBarsData: [
            LineChartBarData(
              spots: chartData.asMap().entries.map((entry) {
                return FlSpot(entry.key.toDouble(), entry.value.value);
              }).toList(),
              isCurved: true,
              gradient: LinearGradient(
                colors: [
                  AppTheme.primaryColor,
                  AppTheme.primaryColor.withValues(alpha: 0.3),
                ],
              ),
              barWidth: 3,
              isStrokeCapRound: true,
              dotData: const FlDotData(
                show: true,
              ),
              belowBarData: BarAreaData(
                show: true,
                gradient: LinearGradient(
                  colors: [
                    AppTheme.primaryColor.withValues(alpha: 0.3),
                    AppTheme.primaryColor.withValues(alpha: 0.1),
                  ],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建强度趋势图表
  Widget _buildIntensityTrendChart(List<MoodRecord> records) {
    final chartData = _prepareIntensityTrendData(records);
    
    return Container(
      height: 250,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: BarChart(
        BarChartData(
          alignment: BarChartAlignment.spaceAround,
          maxY: 10,
          barTouchData: BarTouchData(
            enabled: true,
            touchTooltipData: BarTouchTooltipData(
              getTooltipColor: (group) => AppTheme.primaryColor,
              tooltipRoundedRadius: 8,
              getTooltipItem: (group, groupIndex, rod, rodIndex) {
                return BarTooltipItem(
                  '${chartData[group.x.toInt()].label}\n强度: ${rod.toY.round()}',
                  const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                );
              },
            ),
          ),
          titlesData: FlTitlesData(
            show: true,
            rightTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            topTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            bottomTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                getTitlesWidget: (value, meta) {
                  if (value.toInt() < chartData.length) {
                    return Padding(
                      padding: const EdgeInsets.only(top: 8),
                      child: Text(
                        chartData[value.toInt()].label,
                        style: TextStyle(
                          color: AppTheme.textSecondaryColor,
                          fontSize: 12,
                        ),
                      ),
                    );
                  }
                  return const Text('');
                },
                reservedSize: 30,
              ),
            ),
            leftTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 40,
                interval: 2,
                getTitlesWidget: (value, meta) {
                  return Text(
                    value.toInt().toString(),
                    style: TextStyle(
                      color: AppTheme.textSecondaryColor,
                      fontSize: 12,
                    ),
                  );
                },
              ),
            ),
          ),
          borderData: FlBorderData(
            show: false,
          ),
          barGroups: chartData.asMap().entries.map((entry) {
            return BarChartGroupData(
              x: entry.key,
              barRods: [
                BarChartRodData(
                  toY: entry.value.value,
                  gradient: LinearGradient(
                    colors: [
                      AppTheme.primaryColor,
                      AppTheme.primaryColor.withValues(alpha: 0.7),
                    ],
                    begin: Alignment.bottomCenter,
                    end: Alignment.topCenter,
                  ),
                  width: 20,
                  borderRadius: const BorderRadius.vertical(
                    top: Radius.circular(4),
                  ),
                ),
              ],
            );
          }).toList(),
        ),
      ),
    );
  }

  /// 构建频率图表
  Widget _buildFrequencyChart(List<MoodRecord> records) {
    final chartData = _prepareFrequencyData(records);
    
    return Container(
      height: 200,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: LineChart(
        LineChartData(
          gridData: const FlGridData(show: false),
          titlesData: FlTitlesData(
            show: true,
            rightTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            topTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            bottomTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 30,
                getTitlesWidget: (value, meta) {
                  if (value.toInt() < chartData.length) {
                    return Text(
                      chartData[value.toInt()].label,
                      style: TextStyle(
                        color: AppTheme.textSecondaryColor,
                        fontSize: 10,
                      ),
                    );
                  }
                  return const Text('');
                },
              ),
            ),
            leftTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 40,
                getTitlesWidget: (value, meta) {
                  return Text(
                    value.toInt().toString(),
                    style: TextStyle(
                      color: AppTheme.textSecondaryColor,
                      fontSize: 12,
                    ),
                  );
                },
              ),
            ),
          ),
          borderData: FlBorderData(show: false),
          minX: 0,
          maxX: (chartData.length - 1).toDouble(),
          minY: 0,
          maxY: chartData.map((e) => e.value).reduce(math.max),
          lineBarsData: [
            LineChartBarData(
              spots: chartData.asMap().entries.map((entry) {
                return FlSpot(entry.key.toDouble(), entry.value.value);
              }).toList(),
              isCurved: true,
              color: AppTheme.accentColor,
              barWidth: 3,
              isStrokeCapRound: true,
              dotData: const FlDotData(show: true),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建情绪分布饼图
  Widget _buildMoodDistributionChart(List<MoodRecord> records) {
    final moodCounts = <MoodType, int>{};
    for (final record in records) {
      moodCounts[record.moodType] = (moodCounts[record.moodType] ?? 0) + 1;
    }
    
    final sections = moodCounts.entries.map((entry) {
      final percentage = (entry.value / records.length) * 100;
      return PieChartSectionData(
        color: entry.key.color,
        value: entry.value.toDouble(),
        title: '${percentage.toStringAsFixed(1)}%',
        radius: 100,
        titleStyle: const TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ),
      );
    }).toList();
    
    return Container(
      height: 300,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: PieChart(
              PieChartData(
                sections: sections,
                centerSpaceRadius: 40,
                sectionsSpace: 2,
              ),
            ),
          ),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: moodCounts.entries.map((entry) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4),
                  child: Row(
                    children: [
                      Container(
                        width: 12,
                        height: 12,
                        decoration: BoxDecoration(
                          color: entry.key.color,
                          shape: BoxShape.circle,
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          '${entry.key.emoji} ${entry.key.name}',
                          style: const TextStyle(fontSize: 12),
                        ),
                      ),
                      Text(
                        '${entry.value}',
                        style: const TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                );
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建强度分布图表
  Widget _buildIntensityDistributionChart(List<MoodRecord> records) {
    final intensityCounts = <int, int>{};
    for (final record in records) {
      final intensity = record.intensity.round();
      intensityCounts[intensity] = (intensityCounts[intensity] ?? 0) + 1;
    }
    
    final chartData = List.generate(10, (index) {
      final intensity = index + 1;
      return ChartData(
        label: intensity.toString(),
        value: (intensityCounts[intensity] ?? 0).toDouble(),
      );
    });
    
    return Container(
      height: 250,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: BarChart(
        BarChartData(
          alignment: BarChartAlignment.spaceAround,
          maxY: chartData.map((e) => e.value).reduce(math.max),
          titlesData: FlTitlesData(
            show: true,
            rightTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            topTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            bottomTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                getTitlesWidget: (value, meta) {
                  return Text(
                    chartData[value.toInt()].label,
                    style: TextStyle(
                      color: AppTheme.textSecondaryColor,
                      fontSize: 12,
                    ),
                  );
                },
                reservedSize: 30,
              ),
            ),
            leftTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 40,
                getTitlesWidget: (value, meta) {
                  return Text(
                    value.toInt().toString(),
                    style: TextStyle(
                      color: AppTheme.textSecondaryColor,
                      fontSize: 12,
                    ),
                  );
                },
              ),
            ),
          ),
          borderData: FlBorderData(show: false),
          barGroups: chartData.asMap().entries.map((entry) {
            return BarChartGroupData(
              x: entry.key,
              barRods: [
                BarChartRodData(
                  toY: entry.value.value,
                  gradient: LinearGradient(
                    colors: [
                      AppTheme.accentColor,
                      AppTheme.accentColor.withValues(alpha: 0.7),
                    ],
                    begin: Alignment.bottomCenter,
                    end: Alignment.topCenter,
                  ),
                  width: 20,
                  borderRadius: const BorderRadius.vertical(
                    top: Radius.circular(4),
                  ),
                ),
              ],
            );
          }).toList(),
        ),
      ),
    );
  }

  /// 构建时间分布图表
  Widget _buildTimeDistributionChart(List<MoodRecord> records) {
    final hourCounts = <int, int>{};
    for (final record in records) {
      final hour = record.createdAt.hour;
      hourCounts[hour] = (hourCounts[hour] ?? 0) + 1;
    }
    
    final chartData = List.generate(24, (index) {
      return ChartData(
        label: '${index.toString().padLeft(2, '0')}:00',
        value: (hourCounts[index] ?? 0).toDouble(),
      );
    });
    
    return Container(
      height: 200,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: LineChart(
        LineChartData(
          gridData: const FlGridData(show: false),
          titlesData: FlTitlesData(
            show: true,
            rightTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            topTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            bottomTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                interval: 4,
                reservedSize: 30,
                getTitlesWidget: (value, meta) {
                  if (value.toInt() % 4 == 0 && value.toInt() < 24) {
                    return Text(
                      '${value.toInt()}:00',
                      style: TextStyle(
                        color: AppTheme.textSecondaryColor,
                        fontSize: 10,
                      ),
                    );
                  }
                  return const Text('');
                },
              ),
            ),
            leftTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 40,
                getTitlesWidget: (value, meta) {
                  return Text(
                    value.toInt().toString(),
                    style: TextStyle(
                      color: AppTheme.textSecondaryColor,
                      fontSize: 12,
                    ),
                  );
                },
              ),
            ),
          ),
          borderData: FlBorderData(show: false),
          minX: 0,
          maxX: 23,
          minY: 0,
          maxY: chartData.map((e) => e.value).reduce(math.max),
          lineBarsData: [
            LineChartBarData(
              spots: chartData.asMap().entries.map((entry) {
                return FlSpot(entry.key.toDouble(), entry.value.value);
              }).toList(),
              isCurved: true,
              color: AppTheme.secondaryColor,
              barWidth: 3,
              isStrokeCapRound: true,
              dotData: const FlDotData(show: false),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建统计卡片
  Widget _buildStatisticsCards(List<MoodRecord> records) {
    final totalRecords = records.length;
    final averageIntensity = records.isEmpty
        ? 0.0
        : records.map((r) => r.intensity).reduce((a, b) => a + b) / totalRecords;
    
    final moodCounts = <MoodType, int>{};
    for (final record in records) {
      moodCounts[record.moodType] = (moodCounts[record.moodType] ?? 0) + 1;
    }
    
    // 最常见情绪和媒体记录数统计（暂未使用）
    // final mostCommonMood = moodCounts.entries.isEmpty
    //     ? null
    //     : moodCounts.entries.reduce((a, b) => a.value > b.value ? a : b).key;
    // final recordsWithMedia = records.where((r) => r.mediaAttachments.isNotEmpty).length;
    
    return Row(
      children: [
        Expanded(
          child: _buildStatCard(
            '总记录数',
            totalRecords.toString(),
            Icons.edit_note,
            AppTheme.primaryColor,
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: _buildStatCard(
            '平均强度',
            averageIntensity.toStringAsFixed(1),
            Icons.trending_up,
            AppTheme.accentColor,
          ),
        ),
      ],
    );
  }

  /// 构建统计卡片
  Widget _buildStatCard(String title, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                icon,
                color: color,
                size: 20,
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  title,
                  style: TextStyle(
                    fontSize: 12,
                    color: AppTheme.textSecondaryColor,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: AppTheme.textPrimaryColor,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建模式分析
  Widget _buildPatternAnalysis(List<MoodRecord> records) {
    final patterns = _analyzePatterns(records);
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: patterns.map((pattern) {
          return Padding(
            padding: const EdgeInsets.only(bottom: 12),
            child: Row(
              children: [
                Icon(
                  pattern.icon,
                  color: AppTheme.primaryColor,
                  size: 20,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    pattern.description,
                    style: TextStyle(
                      color: AppTheme.textPrimaryColor,
                    ),
                  ),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  /// 构建标签词云
  Widget _buildTagCloud(List<MoodRecord> records) {
    final tagCounts = <String, int>{};
    for (final record in records) {
      for (final tag in record.tags) {
        tagCounts[tag] = (tagCounts[tag] ?? 0) + 1;
      }
    }
    
    final sortedTags = tagCounts.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));
    
    if (sortedTags.isEmpty) {
      return Container(
        height: 150,
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppTheme.surfaceColor,
          borderRadius: BorderRadius.circular(12),
          boxShadow: AppTheme.cardShadow,
        ),
        child: Center(
          child: Text(
            '暂无标签数据',
            style: TextStyle(
              color: AppTheme.textSecondaryColor,
            ),
          ),
        ),
      );
    }
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: Wrap(
        spacing: 8,
        runSpacing: 8,
        children: sortedTags.take(20).map((entry) {
          final fontSize = math.min(20.0, 12.0 + (entry.value * 2).toDouble());
          final opacity = math.min(1.0, 0.5 + (entry.value / 10));
          
          return Container(
            padding: const EdgeInsets.symmetric(
              horizontal: 12,
              vertical: 6,
            ),
            decoration: BoxDecoration(
              color: AppTheme.primaryColor.withValues(alpha: opacity),
              borderRadius: BorderRadius.circular(16),
            ),
            child: Text(
              '${entry.key} (${entry.value})',
              style: TextStyle(
                fontSize: fontSize,
                color: Colors.white,
                fontWeight: FontWeight.w600,
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  /// 准备情绪趋势数据
  List<ChartData> _prepareMoodTrendData(List<MoodRecord> records) {
    final Map<String, List<double>> dailyIntensities = {};
    
    for (final record in records) {
      final dateKey = '${record.createdAt.month}/${record.createdAt.day}';
      dailyIntensities.putIfAbsent(dateKey, () => []);
      dailyIntensities[dateKey]!.add(record.intensity.toDouble());
    }
    
    return dailyIntensities.entries.map((entry) {
      final averageIntensity = entry.value.reduce((a, b) => a + b) / entry.value.length;
      return ChartData(
        label: entry.key,
        value: averageIntensity,
      );
    }).toList();
  }

  /// 准备强度趋势数据
  List<ChartData> _prepareIntensityTrendData(List<MoodRecord> records) {
    final Map<String, List<double>> dailyIntensities = {};
    
    for (final record in records) {
      final dateKey = '${record.createdAt.month}/${record.createdAt.day}';
      dailyIntensities.putIfAbsent(dateKey, () => []);
      dailyIntensities[dateKey]!.add(record.intensity.toDouble());
    }
    
    return dailyIntensities.entries.map((entry) {
      final averageIntensity = entry.value.reduce((a, b) => a + b) / entry.value.length;
      return ChartData(
        label: entry.key,
        value: averageIntensity,
      );
    }).toList();
  }

  /// 准备频率数据
  List<ChartData> _prepareFrequencyData(List<MoodRecord> records) {
    final Map<String, int> dailyCounts = {};
    
    for (final record in records) {
      final dateKey = '${record.createdAt.month}/${record.createdAt.day}';
      dailyCounts[dateKey] = (dailyCounts[dateKey] ?? 0) + 1;
    }
    
    return dailyCounts.entries.map((entry) {
      return ChartData(
        label: entry.key,
        value: entry.value.toDouble(),
      );
    }).toList();
  }

  /// 分析模式
  List<PatternInsight> _analyzePatterns(List<MoodRecord> records) {
    final patterns = <PatternInsight>[];
    
    if (records.isEmpty) {
      return patterns;
    }
    
    // 分析最活跃的时间段
    final hourCounts = <int, int>{};
    for (final record in records) {
      final hour = record.createdAt.hour;
      hourCounts[hour] = (hourCounts[hour] ?? 0) + 1;
    }
    
    if (hourCounts.isNotEmpty) {
      final mostActiveHour = hourCounts.entries.reduce((a, b) => a.value > b.value ? a : b).key;
      patterns.add(PatternInsight(
        icon: Icons.access_time,
        description: '你最常在 $mostActiveHour:00 记录情绪',
      ));
    }
    
    // 分析情绪趋势
    final recentRecords = records.take(7).toList();
    if (recentRecords.length >= 3) {
      final recentAverage = recentRecords.map((r) => r.intensity).reduce((a, b) => a + b) / recentRecords.length;
      final overallAverage = records.map((r) => r.intensity).reduce((a, b) => a + b) / records.length;
      
      if (recentAverage > overallAverage + 1) {
        patterns.add(PatternInsight(
          icon: Icons.trending_up,
          description: '最近的情绪强度有所提升',
        ));
      } else if (recentAverage < overallAverage - 1) {
        patterns.add(PatternInsight(
          icon: Icons.trending_down,
          description: '最近的情绪强度有所下降',
        ));
      }
    }
    
    // 分析标签使用
    final tagCounts = <String, int>{};
    for (final record in records) {
      for (final tag in record.tags) {
        tagCounts[tag] = (tagCounts[tag] ?? 0) + 1;
      }
    }
    
    if (tagCounts.isNotEmpty) {
      final mostUsedTag = tagCounts.entries.reduce((a, b) => a.value > b.value ? a : b).key;
      patterns.add(PatternInsight(
        icon: Icons.label,
        description: '你最常使用的标签是 "$mostUsedTag"',
      ));
    }
    
    return patterns;
  }
}

/// 时间范围枚举
enum TimeRange {
  week,
  month,
  quarter,
  year,
}

/// 分析类型枚举
enum AnalyticsType {
  mood,
  intensity,
  frequency,
}

/// 图表数据类
class ChartData {
  final String label;
  final double value;
  
  ChartData({
    required this.label,
    required this.value,
  });
}

/// 模式洞察类
class PatternInsight {
  final IconData icon;
  final String description;
  
  PatternInsight({
    required this.icon,
    required this.description,
  });
}